from typing import Optional, List, Dict, Any

from app.util.logger import (
    get_logger,
    logger_context,
    info,
    success,
)
from app.models.device import DeviceInfo


class DeviceService:
    """
    IoT 设备管理服务类
    负责处理所有与设备相关的业务逻辑
    """

    def __init__(self):
        self.logger = get_logger("DeviceService")
        self._devices_data = self._load_mock_devices()
        self.logger.info("📺 设备服务初始化完成")

    def _load_mock_devices(self) -> List[Dict[str, Any]]:
        """加载模拟设备数据"""
        mock_devices = [
            {
                "id": "device_001",
                "name": "温度传感器_01",
                "place_name": "客厅",
                "state": "online",
                "device_type": "temperature_sensor",
                "last_update": "2024-08-29T10:30:00Z",
                "data": {"temperature": 23.5, "humidity": 45},
                "created_at": "2024-01-15T08:00:00Z",
            },
            {
                "id": "device_002",
                "name": "智能灯泡_01",
                "place_name": "卧室",
                "state": "offline",
                "device_type": "smart_light",
                "last_update": "2024-08-29T09:15:00Z",
                "data": {"brightness": 0, "color": "#000000"},
                "created_at": "2024-02-10T12:30:00Z",
            },
            {
                "id": "device_003",
                "name": "空气质量监测器",
                "place_name": "客厅",
                "state": "online",
                "device_type": "air_quality_sensor",
                "last_update": "2024-08-29T10:45:00Z",
                "data": {"pm2_5": 12, "co2": 450, "aqi": 35},
                "created_at": "2024-01-20T14:15:00Z",
            },
            {
                "id": "device_004",
                "name": "智能门锁",
                "place_name": "玄关",
                "state": "online",
                "device_type": "smart_lock",
                "last_update": "2024-08-29T10:50:00Z",
                "data": {"locked": True, "battery": 85, "unlock_count": 127},
                "created_at": "2024-03-05T09:45:00Z",
            },
            {
                "id": "device_005",
                "name": "温度传感器_02",
                "place_name": "厨房",
                "state": "maintenance",
                "device_type": "temperature_sensor",
                "last_update": "2024-08-28T18:20:00Z",
                "data": {"temperature": 25.2, "humidity": 52},
                "created_at": "2024-01-15T08:00:00Z",
            },
            {
                "id": "device_006",
                "name": "智能插座_01",
                "place_name": "客厅",
                "state": "online",
                "device_type": "smart_socket",
                "last_update": "2024-08-29T11:00:00Z",
                "data": {"power": 0, "voltage": 220, "current": 0},
                "created_at": "2024-04-12T16:20:00Z",
            },
        ]

        self.logger.debug(f"📊 加载了 {len(mock_devices)} 个模拟设备")
        return mock_devices

    def get_device_list(
        self,
        place_name: Optional[str] = None,
        state: Optional[str] = None,
        device_type: Optional[str] = None,
        limit: Optional[int] = None,
        offset: int = 0,
    ) -> List[DeviceInfo]:
        """
        根据指定的条件过滤并获取设备列表

        Args:
            place_name: 设备所在位置名称（可选）
            state: 设备状态（可选）
            device_type: 设备类型（可选）
            limit: 返回记录数量限制（可选）
            offset: 跳过记录数量

        Returns:
            设备信息列表，每个元素为 DeviceInfo 对象
        """
        context_logger = logger_context(
            operation="get_device_list",
            place_name=place_name,
            state=state,
            device_type=device_type,
        )

        context_logger.info("🔍 收到设备列表查询请求")

        try:
            filtered_devices = self._devices_data.copy()
            original_count = len(filtered_devices)

            # 按条件过滤
            if place_name:
                filtered_devices = [
                    device
                    for device in filtered_devices
                    if device.get("place_name", "").lower() == place_name.lower()
                ]
                context_logger.debug(
                    f"按位置 '{place_name}' 过滤后，设备数量: {len(filtered_devices)}"
                )

            if state:
                filtered_devices = [
                    device
                    for device in filtered_devices
                    if device.get("state", "").lower() == state.lower()
                ]
                context_logger.debug(
                    f"按状态 '{state}' 过滤后，设备数量: {len(filtered_devices)}"
                )

            if device_type:
                filtered_devices = [
                    device
                    for device in filtered_devices
                    if device.get("device_type", "").lower() == device_type.lower()
                ]
                context_logger.debug(
                    f"按设备类型 '{device_type}' 过滤后，设备数量: {len(filtered_devices)}"
                )

            # 分页处理
            total_count = len(filtered_devices)
            if offset > 0:
                filtered_devices = filtered_devices[offset:]

            if limit and limit > 0:
                filtered_devices = filtered_devices[:limit]

            # 转换为 DeviceInfo 对象列表（适配字段名称）
            device_list = []
            for device in filtered_devices:
                device_info = DeviceInfo(
                    device_no=device["id"],  # 映射 id -> device_no
                    device_name=device["name"],  # 映射 name -> device_name
                    device_type=device["device_type"],
                    place_id=device.get(
                        "place_id", device["id"]
                    ),  # 使用 id 作为 place_id
                    place_name=device["place_name"],
                )
                device_list.append(device_info)

            success(
                f"✅ 设备列表查询完成，从 {original_count} 个设备中筛选出 {total_count} 个符合条件的设备，返回 {len(device_list)} 个设备"
            )
            return device_list

        except Exception as e:
            context_logger.error(f"❌ 查询设备列表时发生错误: {str(e)}")
            context_logger.exception("详细错误信息")
            raise

    def control_device(self, device_no: str, action: str) -> None:
        """
        控制设备

        Args:
            device_no: 设备编号列表
            action: 控制动作

        Raises:
            ValueError: 无效的设备编号
            ValueError: 无效的动作
        """
        context_logger = logger_context(
            operation="control_device",
            device_no=device_no,
        )
        self.logger.info(f"🎛️ 控制设备 {device_no} 执行动作 {action} ...")


class IoTService:
    """
    IoT 统一服务入口
    整合所有子服务，提供统一的业务接口
    """

    def __init__(self):
        self.logger = get_logger("IoTService")
        self.device_service = DeviceService()
        self.logger.info("🚀 IoT 服务初始化完成")

    # 设备相关方法的代理
    def get_device_list(self, **kwargs):
        """获取设备列表（代理方法）"""
        return self.device_service.get_device_list(**kwargs)

    # 控制设备
    def control_device(self, device_no: str, action: str) -> None:
        """控制设备（代理方法）"""
        return self.device_service.control_device(device_no, action)


# 全局服务实例
_iot_service: Optional[IoTService] = None


def get_iot_service() -> IoTService:
    """获取全局IoT服务实例（单例模式）"""
    global _iot_service

    if _iot_service is None:
        _iot_service = IoTService()
        info("🎯 全局 IoT 服务实例已创建")

    return _iot_service
